package com.itheima.reggie.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session) {
        //获取手机号
        String phone = map.get("phone").toString();
        //获取密码
        String code = map.get("code").toString();
        //获取session中的验证码
        Object codeInSession = session.getAttribute(phone);
        //验证码不为空且判断session中的验证码是否与用户输入的验证码相同，相同则登录成功
        if (codeInSession != null && codeInSession.equals(code)) {
            //将用户的手机号向数据库中查询
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            //判断如果没有该用户，则自动完成注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登陆成功后，将用户的id放入session，方便下次查询
            session.setAttribute("user", user.getId());
            return R.success("登录成功");
        }
        return R.error("登录失败");
    }

    /**
     * 手机验证码登录-发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取登录的手机号
        String phone = user.getPhone();
        //判断该手机号是否为空
        if (!StringUtils.isEmpty(phone)) {
            //生产随机验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("验证码：{}", code);
            //todo:发送短信
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage(phone,code);
            //将随机生成的验证码放入session
            session.setAttribute(phone, code);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }
}
